package com.cnswhy.cloud.common.logging.interceptor;

import com.cnswhy.cloud.common.logging.constant.MDCConstant;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.UUID;

/**
 * 后台管理用户session拦截器
 * 
 * @author qiuxw
 *
 */
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
		MDC.clear();
		MDC.put(MDCConstant.LOG_TRACE_ID, UUID.randomUUID().toString().replaceAll("-", ""));
		String remoteIp = request.getHeader("X-Forwarded-For");
		String ua = request.getHeader("ua");
		String version = request.getHeader("VERSION");
		String os = request.getHeader("OS");
		MDC.put(MDCConstant.REMOTE_IP, StringUtils.isEmpty(remoteIp) ? "192.168.0.1" : remoteIp);

		if (request.getHeader(MDCConstant.DEVICE_ID) != null) {
			MDC.put(MDCConstant.DEVICE_ID, request.getHeader(MDCConstant.DEVICE_ID));

		}

		if (request.getHeader(MDCConstant.GPS) != null) {
			MDC.put(MDCConstant.GPS, request.getHeader(MDCConstant.GPS));
		}

		if (request.getHeader(MDCConstant.LOCALIZATION) != null) {
			MDC.put(MDCConstant.LOCALIZATION, request.getHeader(MDCConstant.LOCALIZATION));
		}

		if (request.getHeader(MDCConstant.DEVICE_TYPE) != null) {
			MDC.put(MDCConstant.DEVICE_TYPE, request.getHeader(MDCConstant.DEVICE_TYPE));

		}
		if (handler instanceof HandlerMethod) {
			var hand = (HandlerMethod)handler;
			String methodName = hand.getMethod().getDeclaringClass().getSimpleName() + "." + hand.getMethod().getName();
			MDC.put(MDCConstant.REQ_HANDLER, methodName);
		}
		/*String sessionId = (String)request.getHeader("sessionId");
		HttpSession session = request.getSession();
		log.info("=======================>login interceptor user session id："+sessionId);*/

        // 转移到下一个拦截器
        return super.preHandle(request, response, handler);
    }
	
	public static HashMap<String, String> getBody(HttpServletRequest request) throws IOException
	{
		
		HashMap<String, String> bodyMap = new HashMap<String, String>();
		
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;
		
		try
		{
			InputStream inputStream = request.getInputStream();
			if (inputStream != null)
			{
				bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				char[] charBuffer = new char[128];
				int bytesRead = -1;
				while ((bytesRead = bufferedReader.read(charBuffer)) > 0)
				{
					stringBuilder.append(charBuffer, 0, bytesRead);
					String[] paramsArr = stringBuilder.toString().split("=");
					bodyMap.put(paramsArr[0], paramsArr[1]);
				}
			}
			else
			{
				stringBuilder.append("");
			}
		}
		catch (IOException ex)
		{
			throw ex;
		}
		finally
		{
			if (bufferedReader != null)
			{
				try
				{
					bufferedReader.close();
				}
				catch (IOException ex)
				{
					throw ex;
				}
			}
		}
		
		return bodyMap;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
	{
		super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
	{
		// TODO Auto-generated method stub
		super.afterCompletion(request, response, handler, ex);
	}
}
